<?php

namespace App\Admin\Forms\Service;

use App\Models\Config as Model;
use App\Models\ServiceOrder;
use App\Models\ShopUser;
use App\Models\Worker;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class HandleShop extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
         $res = 0;
         if ($input){
             try {
                 $oid = $input['oid'];
                 $shop_id = $input['shop_id'];
                 $order = ServiceOrder::whereId($oid)->first();
                 $order->shop_id = $shop_id;
                 $res = $order->save();
             }catch (ModelNotFoundException|Exception $e){
                 return $this->response()->error($e->getMessage())->refresh();
             }
         }
         return $this->response()->success($res?'保存成功.':'暂无修改.')->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $oid = $this->payload['oid'];
        $order = ServiceOrder::whereId($oid)->first();
        $city_id = $order->city_id;
        $address = $order->address;
//        $list = ShopUser::query()->where("status",0)->select(["id","name"])->get()->toArray();
//        foreach ($list as $key=>$item){
//            $list[$key]['id'] = $item['id']."shop_id";
//            $list[$key]['children'] = Worker::query()->where("shop_id",$item['id'])->where("status",0)->select(["id","name"])->get()->toArray();
//        }
//        $this->category("worker_id","选择洗车师傅")->options($list);
        $options = ShopUser::query()->where("city_id",$city_id)->select(['id','name','address'])->chunkMap(function ($item){
            $item->text = $item->name."【{$item->address}】";
            return $item;
        })->pluck("text","id");
        $this->display("address","当前订单用户地址")->with(function () use ($address){
            return $address;
        });
        $this->hidden("oid")->default($oid)->value($oid);
        $this->select("shop_id","安排门店")->options($options);
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return $this->getDefault();
    }

    protected function getDefault(){
        return [];
    }
}
